﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Administration;

namespace PhilWicklund.com.SiteCreationWorkflow.Data
{
	public class WorkflowSettings: DataObjectBase
	{
		private static string propertyBagKey = PropertyBagKeys.SiteCreationWorkflowSettings.ToString();
		
		public string listName;
		public bool enableEmails;
		public string scAdminEmail;
		public string siteCreatorEmail;

		public WorkflowSettings() { }

		public WorkflowSettings(
			string listName, bool enableEmails,
			string scadminEmail, string siteCreatorEmail)
		{
			this.listName = listName;
			this.enableEmails = enableEmails;
			this.scAdminEmail = scadminEmail;
			this.siteCreatorEmail = siteCreatorEmail;
		}

		public static WorkflowSettings GetSettings(string webUrl)
		{
			WorkflowSettings settings = new WorkflowSettings();
			SPSecurity.RunWithElevatedPrivileges(delegate()
			{
				using (SPSite site = new SPSite(webUrl))
				{
					string relativeWebUrl = "";
					if (site.Url != webUrl) // NOT Root Web
						relativeWebUrl = webUrl.Substring(site.Url.Length + 1);
					using (SPWeb web = site.OpenWeb(relativeWebUrl))
					{

						if (web.Properties.ContainsKey(propertyBagKey))
						{
							string settingsXml = web.Properties[propertyBagKey];
							settings = (WorkflowSettings)WorkflowSettings.Deserialize(
								typeof(WorkflowSettings), settingsXml);
						}
						else
						{
							settings = new WorkflowSettings(String.Empty, false, String.Empty, String.Empty);
						}
					}
				}
			});
			return settings;
		} 

		public static void SetSettings(SPWeb web, WorkflowSettings settings)
		{
				web.AllowUnsafeUpdates = true;
				settings = InstanciateDefaultsIfNeccessary(settings);
				if (web.Properties.ContainsKey(propertyBagKey))
				{

					web.Properties[propertyBagKey] = settings.ToXml();
					web.Properties.Update();
				}
				else
				{
					web.Properties.Add(propertyBagKey, settings.ToXml());
					web.Properties.Update();
				}
				web.AllowUnsafeUpdates = false;
		}

		public static WorkflowSettings InstanciateDefaultsIfNeccessary(WorkflowSettings settings)
		{
			if (settings.listName == null)
				settings.listName = "Site Approval Requests";
			if (settings.enableEmails == true)
				settings.enableEmails = true;
			if (settings.scAdminEmail == null)
				settings.scAdminEmail = "A new site has been created and is pending approval. Click below to view the request.";
			if (settings.siteCreatorEmail == null)
				settings.siteCreatorEmail = "The status of the site you created has been updated. See below for more information:";

			return settings;
		}

		public override string ToString()
		{
			return this.ToXml();
		}
	}
}
